<template>
  <div style="width: 70%;margin:0 auto">
    <a-form
        v-bind="formItemLayout"
        :model="formState"
        @finish="onFinish"
    >
      <a-form-item label="上传封面" v-bind="validateInfos.cover_id">
        <a-upload
            accept="image/*"
            v-model:file-list="coverList"
            :action="BASE_UPLOAD_FILE"
            list-type="picture-card"
            @preview="handlePreview"
        >
          <div v-if="coverList.length < 1">
            <PlusOutlined/>
            <div style="margin-top: 8px">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="文章名字" v-bind="validateInfos.name">
        <a-input v-model:value="formState.name" style="width: 30%"/>
      </a-form-item>
      <a-form-item label="文章内容" v-bind="validateInfos.content">
        <WangEdit :value-html="valueHtml" :content="detailData?.content??null"
                  @set-value-html="(v:string)=>valueHtml = v"/>
      </a-form-item>
      <!-- 分类 -->
      <CategoryFrom :id="route.params.id"
                    :validate-infos="validateInfos"
                    :state="formState"
                    :type-id="detailData?.dict?.type_id??''"/>
      <a-form-item :wrapper-col="{ offset: 9 }">
        <a-button type="primary" html-type="submit">提交</a-button>
        <a-button style="margin-left: 10px" @click="resetFields">重置</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import {useForm} from "ant-design-vue/es/form";
import {BASE_UPLOAD_FILE} from "@/axios";
import {message, UploadProps} from "ant-design-vue";
import {getBase64} from "@/util";
import {useRoute, useRouter} from "vue-router";
import type {ArticleDataType, ArticleFormType} from "@/util/publicType";
import CategoryFrom from "@/components/CategoryFrom.vue";
import {addArticle, articleDetail, editArticle} from "@/api/api";
import type {AxiosResponse} from "axios";
import WangEdit from "@/components/WangEdit.vue";
import {useInfoStore} from "@/stores/userInfo";


// 编辑器内容
const valueHtml = ref<string>("");
// 封面list
const coverList = ref<any>([]);
// 是否预览
const previewVisible = ref(false);
// 预览地址
const previewImage = ref('');
// 预览标题
const previewTitle = ref('');
// 路由信息
const route = useRoute();
// 当前用户信息
const {infoData} = useInfoStore();
// 跳转
const router = useRouter();
// 是否为更新
const isUpdate = route.path.indexOf("update") >= 0;
// 详情数据
const detailData = ref<ArticleDataType | null>(null);
// 表单布局
const formItemLayout = {
  labelCol: {
    sm: {span: 5},
  },
  wrapperCol: {
    sm: {span: 16},
  },
};

// 表单初始值
let formState = reactive<ArticleFormType>({
  name: "",
  cover_id: "",
  content: "",
  category_id: "",
  username: ""
});

// 输入限制
const ruleRef = reactive({
  name: [
    {
      required: true,
      message: "请输入标题"
    }
  ],
  cover_id: [
    {
      required: false
    }
  ],
  content: [
    {
      required: false
    }
  ],
  category_id: [
    {
      required: true,
      message: "至少选择一项"
    }
  ]
})

// 文章详情
const getDetail = () => {
  articleDetail(route.params.id as string).then((r: AxiosResponse) => {
    const data: ArticleDataType = r.data.data.data;
    detailData.value = data;
    formState = Object.assign(formState, {
      content: data?.content ?? '',
      cover_id: data.cover.id,
      category_id: data.category_id,
      name: data.name,
    });
    const cover: any = {
      uid: data?.cover?.id,
      status: 'done',
      name: data?.cover?.type,
      url: data?.cover?.path
    };
    coverList.value = [cover];
  }, err => message.error(err))
}

onMounted(() => {
  // 如果为更新页面，直接请求数据
  if (isUpdate) {
    getDetail();
  }
})
// 预览操作
const handlePreview = async (file: UploadProps['fileList'][number]) => {
  // 转换格式
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  // 预览地址
  previewImage.value = file.url || file.preview;
  // 预览显示
  previewVisible.value = true;
  // 预览名字
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

// 表单事件
const {resetFields, validate, validateInfos} = useForm(formState, ruleRef);

// 表单完成
const onFinish = () => {
  let request: Promise<AxiosResponse>;
  validate().then(() => {
    const cover_id = coverList.value[0]?.response?.data?.data?.id;
    formState.cover_id = cover_id ? cover_id : coverList.value[0]?.uid;
    if (!formState.cover_id) {
      return message.error("请上传封面");
    }
    formState.content = valueHtml.value;
    formState.username = infoData.username;
    if (isUpdate) {
      request = editArticle((route.params.id as string), formState);
    } else {
      request = addArticle(formState);
    }
    request.then(() => {
      // 清除数据
      resetFields();
      coverList.value = [];
      if (isUpdate) {
        router.push(`/article/${detailData.value?.category_id}`)
      }
      detailData.value = null;
      message.success("操作成功");
    }, err => message.error(err))
  })
}

</script>